//
//  TXOAuthViewController.swift
//  MicroBlog
//
//  Created by Jokin on 2017/3/29.
//  Copyright © 2017年 jokin. All rights reserved.
//

import UIKit
import SVProgressHUD


// 微博appkey
let AppKey = "3535476032"
// 微博的AppSearet
let AppSearet = "9627ab6441e717c7c08e199ee262c787"
// 授权回调地址
let ComeBackUrl = "http://www.itcast.cn/"

class TXOAuthViewController: UIViewController {

    
    lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        CreatNav()
        requestOAuth()
        webView.delegate = self
        
    }
    
    private func CreatNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(TouchCancleAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imageName: nil, target: self, action: #selector(touchAutoFillAction))
        
        
    }
    
    
    
    // 自动填充按钮
    func touchAutoFillAction() {
        print("填充")
    }
    
    
    // 取消按钮
    func TouchCancleAction() {
        print("取消")
    }
    
    
    func requestOAuth() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(ComeBackUrl)"
        let request = URLRequest(url: URL(string: urlStr)!)
        webView.loadRequest(request)
        
        
        
    }
    
    
 

}

extension TXOAuthViewController:UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlStr = request.url?.absoluteString else {
            return false
        }
        
        if !urlStr.hasPrefix(ComeBackUrl) {
            return true
        }
        if let query = request.url?.query, query.hasPrefix("code="){
            let code = query.substring(from: "code=".endIndex)
            TXUserAccountViewModel.shareUserViewModel.requestAcceesToken(code: code, callBack: { (isSucceed) in
                if isSucceed {
                    print("登陆成功")
                    
                   self.dismiss(animated: false, completion: { 
                    NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                   })
                }else {
                    print("登陆失败")
                }
            })
            
        }else {
            dismiss(animated: true, completion: nil)
        }
        return false
        
        
        
        
    }
    

    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    
}











